package cn.fch.gotrip.util;

import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: gotrip
 * @description:
 * @CreatedBy: fch
 * @create: 2023-01-24 13:21
 **/
@Component
public class OrderIdUtil {

    private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyyMMddhhmmssSSS");
    private static int tempTravelOrderId = 999;
    private static int tempHotelOrderId = 999;
    private static final Lock TRAVEL_ORDER_LOCK = new ReentrantLock();
    private static final Lock HOTEL_ORDER_LOCK = new ReentrantLock();

    public String creatTravelOrderIdLength21(Date now) {
        try {
            if (TRAVEL_ORDER_LOCK.tryLock(1000, TimeUnit.MILLISECONDS)) {
                tempTravelOrderId++;
                if (tempTravelOrderId > 9999) {
                    tempTravelOrderId = 1000;
                }
                return getOrderId(tempTravelOrderId, now);
            } else {
                return creatTravelOrderIdLength21(now);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        } finally {
            TRAVEL_ORDER_LOCK.unlock();
        }
    }

    public String creatHotelOrderIdLength21(Date now) {
        try {
            if (HOTEL_ORDER_LOCK.tryLock(1000, TimeUnit.MILLISECONDS)) {
                tempHotelOrderId++;
                if (tempHotelOrderId > 9999) {
                    tempHotelOrderId = 1000;
                }
                return getOrderId(tempHotelOrderId, now);
            } else {
                return creatHotelOrderIdLength21(now);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        } finally {
            HOTEL_ORDER_LOCK.unlock();
        }
    }

    private String getOrderId(int temp, Date date){
        return SIMPLE_DATE_FORMAT.format(date) + temp;
    }
}
